﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_MasterData_Product : System.Web.UI.UserControl
{
    DBDataContext db;
    DatabaseHelper helper;
    ProProduct pro;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           ResetForm();
        }
    }
    private string GernerateCode()
    {
        string strCode = string.Empty;
        try
        {
            db = new DBDataContext();
            var PurchaseOrderMax = db.Products.Max(d => d.OrderNumber);
            int MaxOrderNumber = (PurchaseOrderMax == null ? 0 : Convert.ToInt32(PurchaseOrderMax)) + 1;
            String strLastCode = "0000000" + MaxOrderNumber.ToString();
            strCode = "SP" + strLastCode.Substring(strLastCode.Length - 7);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-GernerateCode:" + ex.Message);
            ResetForm();
        }
        return strCode;
    }
    private void ResetForm()
    {
        try
        {
            txtProductCode.Text = GernerateCode();
            Utils.loadProductType(cbProperty,0, "P");
            Utils.loadProductType(cbProductTypeID, 0, "T");
            Utils.loadProductType(cbProductTypeSearch, 1, "T");
            //rtpFromDateSearch.SelectedDate = DateTime.Now.Date;
            //rtpToDateSearch.SelectedDate = DateTime.Now.Date;
            txtProductCodeSearch.Text ="";
            txtProductNameSearch.Text = "";
            txtProductName.Text = "";
            txtSortOrder.Text = "";
            txtUnit.Text = "";
            //txtPrice.Text = "";
            RadEditorContent.Content = "";
            hidOldImagePath.Value = "";
            img.Visible = false;
            ViewState["ProductID"] = null;
            btnCancel.Enabled = false;
            //btnExport.Enabled = false;
            //Dinh nghia gia ban
            Utils.loadProductToComboPrice(cbProduct, 1, "R");
            Utils.loadLocationToRadListBox(rlbLocation);
            gv_Price.DataSource = new DataTable();
            gv_Price.DataBind();
                
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-ResetForm:" + ex.Message);
        }
    }
    private void fillData(ProProduct pro)
    {
        try
        {
            txtProductCode.Text = pro.strProductCode;
            txtProductName.Text = pro.strProductName;
            RadEditorContent.Content = pro.strContent;
            cbType.SelectedValue = pro.strType;
            if (cbType.SelectedValue == "P")//Qua tang
            {
                //txtPrice.Enabled = false;
                cbIsNew.Enabled = false;
                cbProductTypeID.Enabled = false;
                cbProperty.Enabled = false;
                cbIsPromotion.Enabled = false;
            }
            else//Gao
            {
                //txtPrice.Enabled = true;
                cbIsNew.Enabled = true;
                cbProductTypeID.Enabled = true;
                cbProperty.Enabled = true;
                cbIsPromotion.Enabled = true;
                cbIsPromotion.SelectedValue = pro.strIsPromotion;
            }
            cbIsNew.SelectedValue = pro.strIsNew;
            cbProductTypeID.SelectedValue = pro.iProductType.ToString();
            cbProperty.SelectedValue = pro.iProperty.ToString();
            txtSortOrder.Text = String.Format("{0:N0}", pro.iSortOrder);
            //txtPrice.Text = String.Format("{0:#,#.##}", pro.dPrice);
            txtUnit.Text = pro.strUnit;
            //txtStatus.Text = pro.strStatusName;
            hidOldImagePath.Value = pro.strOldImagePath;
            img.ImageUrl = Utils.getUrlImage() + pro.strImagePath;
            img.Visible = true;
            btnSave.Enabled = true;
            //SetStatus(pro.strStatus);
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-fillData:" + ex.Message);
        }
    }
    private void delete(int ID)
    {
        
        db = new DBDataContext();
        //db.Connection.Open();
        Product obj = db.Products.FirstOrDefault(x => x.ID == ID);

        obj.LastUpdatedDateTime = DateTime.Now;
        obj.LastUpdatedBy = Session["Username"].ToString();
        obj.Status = 'I';

        db.Update<Product>(obj);
        db.SubmitChanges();
        //db.Connection.Close();
        //Reset();

        var cus = (from c in db.Products
                   where c.ID == ID
                   select c).FirstOrDefault();
        Utils.DeleteFileFromServer(cus.ImagePath);
    }
    private bool save(ProProduct pro)
    {
        db = new DBDataContext();
        //db.Connection.Open();
        try
        {
            if (ViewState["ProductID"] == null)//Insert I
            {
                Product obj = new Product();

                string strPurchaseOrderCode = GernerateCode();
                
                obj.ProductCode = strPurchaseOrderCode;
                obj.ProductName = pro.strProductName;
                obj.OrderNumber = Convert.ToInt32(Utils.KillChars(strPurchaseOrderCode.Substring(2, strPurchaseOrderCode.Length - 2)));
                obj.Content = pro.strContent;
                obj.ProductTypeID = pro.iProductType;
                obj.ProductTypeID1 = pro.iProperty;
                obj.IsPromotion = Convert.ToByte(pro.strIsPromotion);
                //obj.Price = pro.dPrice;
                obj.Unit = pro.strUnit;
                obj.ImagePath = pro.strImagePath;
                obj.IsNew = pro.strIsNew;
                obj.ProductType = pro.strType;
                obj.SortOrder = pro.iSortOrder;
                obj.CreatedDateTime = DateTime.Now;
                obj.LastUpdatedDateTime = DateTime.Now;
                obj.CreatedBy = pro.strCreatedBy;
                obj.LastUpdatedBy = pro.strLastUpdatedBy;
                obj.Status = Convert.ToChar(pro.strStatus);
                db.Insert<Product>(obj);
                db.SubmitChanges();
                ViewState["ProductID"] = obj.ID;
            }
            else
            {
                int iProductID = Convert.ToInt32(ViewState["ProductID"]);
                Product obj = db.Products.FirstOrDefault(x => x.ID == iProductID);
                obj.ProductName = pro.strProductName;
                obj.Content = pro.strContent;
                obj.ProductTypeID = pro.iProductType;
                obj.ProductTypeID1 = pro.iProperty;
                obj.IsPromotion = Convert.ToByte(pro.strIsPromotion);
                obj.IsNew = pro.strIsNew;
                obj.ProductType = pro.strType;
                obj.Unit = pro.strUnit;
                obj.ImagePath = pro.strImagePath;
                obj.SortOrder = pro.iSortOrder;
                obj.LastUpdatedDateTime = DateTime.Now;
                obj.LastUpdatedBy = pro.strLastUpdatedBy;
                obj.Status = Convert.ToChar(pro.strStatus);
                //db.Update<Product>(obj);
                db.SubmitChanges();
            }
            //db.Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-Save:" + ex.Message);
            return false;
        }

    }
    private void getDataSearch()
    {
        pro = new ProProduct();
        pro.strProductNameSearch = Utils.KillChars(txtProductNameSearch.Text.Trim());
        pro.strProductCodeSearch = Utils.KillChars(txtProductCodeSearch.Text.Trim());
        pro.strTypeSearch = Utils.KillChars(cbTypeSearch.SelectedValue.Trim().ToString());
        pro.strIsNewSearch = Utils.KillChars(cbIsNewSearch.SelectedValue.Trim().ToString());
        pro.iProductTypeSearch = Convert.ToInt32(Utils.KillChars(cbProductTypeSearch.SelectedValue == "" ? "-1" : cbProductTypeSearch.SelectedValue));
        pro.strIsPromotionSearch = Utils.KillChars(cbIsPromotionSearch.SelectedValue == "" ? "-1" : cbIsPromotionSearch.SelectedValue);
        //pro.strStartDate = Utils.KillChars(this.rtpFromDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpFromDateSearch.SelectedDate));
        //pro.strEndDate = Utils.KillChars(this.rtpToDateSearch.SelectedDate == null ? "" : String.Format("{0:dd/MM/yyyy}", this.rtpToDateSearch.SelectedDate));

        loadData(pro);
    }
    private void getPriceSearch()
    {
        try
        {
            IList<RadListBoxItem> collection = rlbLocation.CheckedItems;
            int[] listLocationID;
            if (collection.Count > 0)
            {
                listLocationID = new int[collection.Count];
            }
            else
            {
                listLocationID = new int[1];
                listLocationID[0] = 0;
            }

            for (int i = 0; i < collection.Count; i++)
            {
                listLocationID[i] = Convert.ToInt32(collection[i].Value);
            }

            string strProductID = cbProduct.SelectedValue.ToString();
            strProductID = strProductID == "" ? "0" : strProductID;
            DataTable dt = loadPrice(0, Convert.ToInt32(strProductID), listLocationID);
            if (dt.Rows.Count > 0)
            {
                gv_Price.Height = 250;
                gv_Price.ClientSettings.Scrolling.AllowScroll = true;
                gv_Price.ClientSettings.Scrolling.UseStaticHeaders = true;
                gv_Price.VirtualItemCount = Convert.ToInt32(dt.Rows.Count);
                gv_Price.DataSource = dt;
            }
            //gv_Price.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-getPriceSearch:" + ex.Message.ToString());
        }
    }
    private void loadData(ProProduct pro)
    {
        try
        {
            DataTable dt = dtProduct(pro);
            if (dt.Rows.Count > 0)
            {
                gvData.Height = 250;
                gvData.ClientSettings.Scrolling.AllowScroll = true;
                gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                gvData.VirtualItemCount = Convert.ToInt32(dt.Rows[0]["TotalRows"]);
                //btnExport.Enabled = true;
                div_TotalRows.InnerText ="Kết quả tìm kiếm: "  + String.Format("{0:N0}",Convert.ToInt32(dt.Rows[0]["TotalRows"]));
                gvData.DataSource = dt;
            }
            else
            {
                gvData.DataSource = new DataTable();
                div_TotalRows.InnerText = "Kết quả tìm kiếm: 0" ;
            }

            //gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-loadData:" + ex.Message);
        }
    }
    private DataTable dtProduct(ProProduct pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.PageSize;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramNewsID = helper.Parameter;
            paramNewsID.ParameterName = "ProductID";
            paramNewsID.DbType = DbType.Int32;
            paramNewsID.Value = -1;
            helper.AddParameter(paramNewsID);

            System.Data.Common.DbParameter paramNewsType = helper.Parameter;
            paramNewsType.ParameterName = "ProductCode";
            paramNewsType.DbType = DbType.String;
            paramNewsType.Value = pro.strProductCodeSearch;
            helper.AddParameter(paramNewsType);

            System.Data.Common.DbParameter paramProductName = helper.Parameter;
            paramProductName.ParameterName = "ProductName";
            paramProductName.DbType = DbType.String;
            paramProductName.Value = pro.strProductNameSearch;
            helper.AddParameter(paramProductName);

            System.Data.Common.DbParameter paramIsNew = helper.Parameter;
            paramIsNew.ParameterName = "IsNew";
            paramIsNew.DbType = DbType.String;
            paramIsNew.Value = pro.strIsNewSearch;
            helper.AddParameter(paramIsNew);

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProductTypeId = helper.Parameter;
            paramProductTypeId.ParameterName = "ProductTypeId";
            paramProductTypeId.DbType = DbType.Int32;
            paramProductTypeId.Value = pro.iProductTypeSearch;
            helper.AddParameter(paramProductTypeId);

            System.Data.Common.DbParameter pIsPromotion = helper.Parameter;
            pIsPromotion.ParameterName = "IsPromotion";
            pIsPromotion.DbType = DbType.Int32;
            pIsPromotion.Value = Convert.ToInt32(pro.strIsPromotionSearch);
            helper.AddParameter(pIsPromotion);


            //System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            //paramStartDate.ParameterName = "StartDate";
            //paramStartDate.DbType = DbType.String;
            //paramStartDate.Value = pro.strStartDate;
            //helper.AddParameter(paramStartDate);

            //System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            //paramEndDate.ParameterName = "EndDate";
            //paramEndDate.DbType = DbType.String;
            //paramEndDate.Value = pro.strEndDate;
            //helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-dtProduct:" + ex.Message);
            return new DataTable();
        }
    }
    private DataTable dtProductExport(ProProduct pro)
    {
        try
        {
            int PageNumber = gvData.CurrentPageIndex + 1;
            int PageSize = gvData.VirtualItemCount;

            helper = new DatabaseHelper();
            System.Data.Common.DbParameter paramNewsID = helper.Parameter;
            paramNewsID.ParameterName = "ProductID";
            paramNewsID.DbType = DbType.Int32;
            paramNewsID.Value = -1;
            helper.AddParameter(paramNewsID);

            System.Data.Common.DbParameter paramNewsType = helper.Parameter;
            paramNewsType.ParameterName = "ProductCode";
            paramNewsType.DbType = DbType.String;
            paramNewsType.Value = pro.strProductCodeSearch;
            helper.AddParameter(paramNewsType);

            System.Data.Common.DbParameter paramProductName = helper.Parameter;
            paramProductName.ParameterName = "ProductName";
            paramProductName.DbType = DbType.String;
            paramProductName.Value = pro.strProductNameSearch;
            helper.AddParameter(paramProductName);

            System.Data.Common.DbParameter paramIsNew = helper.Parameter;
            paramIsNew.ParameterName = "IsNew";
            paramIsNew.DbType = DbType.String;
            paramIsNew.Value = pro.strIsNewSearch;
            helper.AddParameter(paramIsNew);

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "ProductType";
            paramType.DbType = DbType.String;
            paramType.Value = pro.strTypeSearch;
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProductTypeId = helper.Parameter;
            paramProductTypeId.ParameterName = "ProductTypeId";
            paramProductTypeId.DbType = DbType.Int32;
            paramProductTypeId.Value = pro.iProductTypeSearch;
            helper.AddParameter(paramProductTypeId);

            System.Data.Common.DbParameter pIsPromotion = helper.Parameter;
            pIsPromotion.ParameterName = "IsPromotion";
            pIsPromotion.DbType = DbType.Int32;
            pIsPromotion.Value = Convert.ToInt32(pro.strIsPromotionSearch);
            helper.AddParameter(pIsPromotion);


            //System.Data.Common.DbParameter paramStartDate = helper.Parameter;
            //paramStartDate.ParameterName = "StartDate";
            //paramStartDate.DbType = DbType.String;
            //paramStartDate.Value = pro.strStartDate;
            //helper.AddParameter(paramStartDate);

            //System.Data.Common.DbParameter paramEndDate = helper.Parameter;
            //paramEndDate.ParameterName = "EndDate";
            //paramEndDate.DbType = DbType.String;
            //paramEndDate.Value = pro.strEndDate;
            //helper.AddParameter(paramEndDate);

            System.Data.Common.DbParameter paramPageNumber = helper.Parameter;
            paramPageNumber.ParameterName = "PageNumber";
            paramPageNumber.DbType = DbType.Int32;
            paramPageNumber.Value = PageNumber;
            helper.AddParameter(paramPageNumber);

            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = PageSize;
            helper.AddParameter(paramPageSize);
            DataTable dt = helper.ExecuteDataTable("Admin_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-dtProductExport:" + ex.Message);
            return new DataTable();
        }
    }
    private DataTable loadPrice(int ID = 0, int iProductID = 0, int[] listLocationID = null)
    {
        DataTable dt = new DataTable();
        try
        {

            db = new DBDataContext();
            var list1 = (from a in db.DefinitionPrices
                        join b in db.Products on a.ProductID equals b.ID
                        join c in db.Locations on a.LocationID equals c.ID
                        where a.Status == 'A' && (a.ID == ID || ID == 0) && (b.ID == iProductID || iProductID == 0)
                                    && (listLocationID.Contains(c.ID) || listLocationID.Contains(0))
                        orderby a.LastUpdatedDateTime descending
                        select new
                        {
                           
                            DefinitionPriceID = a.ID,
                            ProductName = b.ProductCode + "-" + b.ProductName,
                            ProductID = b.ID,
                            Price = a.Price,
                            LocationName = c.LocationName,
                            LocationID = c.ID,
                            LastUpdatedBy = a.LastUpdatedBy,
                            LastUpdatedDateTime = string.Format("{0:dd/MM/yy}", a.LastUpdatedDateTime),
                        });
            //Xu ly RowID
            var list = list1.AsEnumerable().Select((b, index) => new
                            {
                                DefinitionPriceID = b.DefinitionPriceID,
                                ProductName = b.ProductName,
                                ProductID = b.ProductID,
                                Price = b.Price,
                                LocationName = b.LocationName,
                                LocationID = b.LocationID,
                                LastUpdatedBy = b.LastUpdatedBy,
                                LastUpdatedDateTime = string.Format("{0:dd/MM/yy}", b.LastUpdatedDateTime),
                                RowID = index + 1
                            }).ToList();
            dt = list.ToDataTable();
            if (dt.Rows.Count > 0)
                div_TotalPrice.InnerText = "Kết quả tìm kiếm: " + String.Format("{0:N0}", dt.Rows.Count);
            
            else
                div_TotalPrice.InnerText = "Kết quả tìm kiếm: 0" ;
        }
        
        catch (Exception ex) {
            ControlUtil.LogError("Product Page-loadPrice:" + ex.Message.ToString());
            return null;
        }
        return dt;
    }    
    #region Properties
    public class ProProduct
    {
        public string strProductCode { get; set; }
        public string strProductCodeSearch { get; set; }
        public string strProductName { get; set; }
        public string strProductNameSearch { get; set; }
        public string strImagePath { get; set; }
        public string strStatus { get; set; }
        public string strStatusName { get; set; }
        public string strOldImagePath { get; set; }
        public string strStartDate { get; set; }
        public string strEndDate { get; set; }
        public string strContent { get; set; }
        public string strIsPromotion { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public DateTime UpdatedDateTime { get; set; }
        public string strCreatedBy { get; set; }
        public string strLastUpdatedBy { get; set; }
        public string strIsNew { get; set; }
        public string strIsNewSearch { get; set; }
        public string strUnit { get; set; }
        public string strType { get; set; }
        public string strTypeSearch { get; set; }
        public string strIsPromotionSearch { get; set; }
        public int? iProductType { get; set; }
        public int? iProductTypeSearch { get; set; }
        public int? iOrderNumber { get; set; }
        public int? iProperty { get; set; }
        public double? dPrice { get; set; }
        public int? iID { get; set; }
        public int iSortOrder { get; set; }
    }
    #endregion End Properties

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["Username"] != null)
            {
                pro = new ProProduct();
                pro.strProductName = Utils.KillChars(txtProductName.Text.Trim());
                pro.strContent = RadEditorContent.Content.Trim();
                pro.strType = Utils.KillChars(cbType.SelectedValue.ToString());
                pro.strIsNew = Utils.KillChars(cbIsNew.SelectedValue.ToString());
                pro.iProductType = Convert.ToInt32(cbProductTypeID.SelectedValue.ToString() == "" ? "0" : cbProductTypeID.SelectedValue.ToString());
                pro.iProperty = Convert.ToInt32(cbProperty.SelectedValue.ToString() == "" ? "0" : cbProperty.SelectedValue.ToString());
                pro.iSortOrder = Utils.KillChars((txtSortOrder.Text.Trim())) == "" ? 0 : Convert.ToInt32(Utils.KillChars((txtSortOrder.Text.Trim())));

                pro.strCreatedBy = Session["Username"].ToString();
                pro.strLastUpdatedBy = Session["Username"].ToString();
                if (string.IsNullOrEmpty(pro.strProductName))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập tên sản phẩm!");
                    txtProductName.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(pro.strType))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại gạo: Gạo hoặc Quà tặng!");
                    cbType.Focus();
                    return;
                }

                if (pro.strType == "R")//Gao
                {
                    
                    if (string.IsNullOrEmpty(pro.strIsNew))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn loại hình thức!");
                        cbIsNew.Focus();
                        return;
                    }
                    if (string.IsNullOrEmpty(cbIsPromotion.SelectedValue.Trim()))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn khuyến mãi!");
                        cbIsPromotion.Focus();
                        return;
                    }
                    pro.strIsPromotion = cbIsPromotion.SelectedValue.Trim();
                    pro.strUnit = "kg";
                }
                else {//Qua tang

                    pro.dPrice = 0;
                    pro.strIsNew = null;
                    pro.iProductType = 0;
                    pro.iProperty = 0;
                    pro.strIsPromotion = "0";

                    if(string.IsNullOrEmpty(txtUnit.Text.Trim())){
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập đơn vị!");
                        txtUnit.Focus();
                        return;
                    }
                    pro.strUnit = Utils.KillChars(txtUnit.Text.Trim());
                }

                //Luu hinh vao Disk
                if (fuImagePath.HasFile)
                {
                    FileInfo f = new FileInfo(fuImagePath.FileName);
                    if (f != null && (f.Extension.ToLower() != ".gif" && f.Extension.ToLower() != ".jpg" && f.Extension.ToLower() != ".jpeg" && f.Extension.ToLower() != ".png"))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Chỉ được upload file dạng .gif, .jpg, .jpeg, .png");
                        return;
                    }
                    if (f != null && fuImagePath.FileBytes.Length > (512 * 1024))
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Dung lượng hình ảnh không quá 500kb");
                        return;
                    }
                    //Delete file cu
                    if (!string.IsNullOrEmpty(hidOldImagePath.Value))
                        Utils.DeleteFileFromServer(hidOldImagePath.Value);

                    string strPath = "/Upload/Product/";
                    pro.strImagePath = strPath + Path.GetFileName(fuImagePath.FileName);
                    Utils.UploadFileToFTP(fuImagePath, strPath);
                }
                else
                {
                    if (!string.IsNullOrEmpty(hidOldImagePath.Value))
                        pro.strImagePath = hidOldImagePath.Value;
                }
                //End luu hinh vao Disk
                pro.strStatus = "A";
                if (save(pro))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu tin thành công!"); 
                    this.btnSave.Enabled = false;
                    //this.btnFinish.Enabled = true;
                }
                else
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            }
        }
        catch (Exception ex) {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            ControlUtil.LogError("Product Page-btnSave_Click:" + ex.Message);
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            gvData.Height = 250;
            gvData.Visible = true;
            getDataSearch();
            gvData.DataBind();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-btnSearch_Click:" + ex.Message);
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        ResetForm();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {

            if (ViewState["ProductID"] != null)
            {
                try
                {
                    delete(Convert.ToInt32(ViewState["ProductID"]));
                    ResetForm();
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                    gvData.Rebind();
                }
                catch (Exception ex)
                {
                    ControlUtil.LogError("Product Page-btnCancel_Click:" + ex.Message);
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                }
            }
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        getDataSearch();
        gvData.DataBind();
    }
    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {

            //Ham phan trang: Paging
            if (RadPageView2.Selected)
            {
                TabStrip1.SelectedIndex = 1;
                gvData.Height = 250;
                gvData.Visible = true;
                getDataSearch();
            }
            else
            {
                gvData.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void cbType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (cbType.SelectedValue == "P")//Qua tang
        {
            //txtPrice.Enabled = false;
            cbIsNew.Enabled = false;
            cbProductTypeID.Enabled = false;
            cbProperty.Enabled = false;
            txtUnit.ReadOnly = false;
            cbIsPromotion.Enabled = false;
        }
        if (cbType.SelectedValue == "R")//Gao
        {
            txtUnit.Text = "kg";
            txtUnit.ReadOnly = true;
            
            //txtPrice.Enabled = true;
            cbIsNew.Enabled = true;
            cbProductTypeID.Enabled = true;
            cbProperty.Enabled = true;
            cbIsNewSearch.Enabled = true;
            cbProductTypeSearch.Enabled = true;
            cbIsPromotion.Enabled = true;
        }
        if (cbTypeSearch.SelectedValue == "P")//Qua tang
        {
            cbIsNewSearch.Enabled = false;
            cbProductTypeSearch.Enabled = false;
            cbIsPromotionSearch.Enabled = false;
        }
        if (cbTypeSearch.SelectedValue == "R")//Gao
        {
            cbIsNewSearch.Enabled = true;
            cbProductTypeSearch.Enabled = true;
            cbIsPromotionSearch.Enabled = true;
        }
    }
    protected void gvData_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            if (Session["Username"] != null)
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                pro = new ProProduct();
                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView1.Selected = true;
                        TabStrip1.SelectedIndex = 0;

                        System.Data.Common.DbParameter paramNewsID = helper.Parameter;
                        paramNewsID.ParameterName = "ProductID";
                        paramNewsID.DbType = DbType.Int32;
                        paramNewsID.Value = ID;
                        helper.AddParameter(paramNewsID);
                        DataTable dt = helper.ExecuteDataTable("Admin_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
                        if (dt.Rows.Count > 0)
                        {
                            pro.strProductCode = dt.Rows[0]["ProductCode"].ToString();
                            pro.strProductName = dt.Rows[0]["ProductName"].ToString();
                            pro.strType = dt.Rows[0]["ProductType"].ToString();
                            pro.strContent = dt.Rows[0]["Content"].ToString();
                            pro.iSortOrder = Convert.ToInt32(dt.Rows[0]["SortOrder"].ToString());
                            //pro.dPrice = Convert.ToDouble(dt.Rows[0]["Price"].ToString());
                            pro.strUnit = dt.Rows[0]["Unit"].ToString();
                            pro.strIsNew = dt.Rows[0]["IsNew"].ToString();
                            pro.iProductType = Convert.ToInt32(dt.Rows[0]["ProductTypeID"].ToString());
                            pro.iProperty = Convert.ToInt32(dt.Rows[0]["ProductTypeID1"].ToString());
                            pro.strImagePath = dt.Rows[0]["ImagePath"].ToString() == "" ? "/NoImage.jpg" : dt.Rows[0]["ImagePath"].ToString();
                            pro.strOldImagePath = dt.Rows[0]["ImagePath"].ToString();
                            //pro.strStatusName = dt.Rows[0]["StatusName"].ToString();
                            //pro.strStatus = dt.Rows[0]["Status"].ToString();
                            pro.strIsPromotion = dt.Rows[0]["IsPromotion"].ToString();
                            fillData(pro);
                            ViewState["ProductID"] = ID;
                            btnCancel.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("Product Page-gvData_ItemCommand-EditItem:" + ex.Message);
                    }
                }
                else if (commandName == "DeleteItem")
                {
                    try
                    {
                        delete(ID);
                        ResetForm();
                        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                        gvData.Rebind();
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("Product Page-gvData_ItemCommand-DeleteItem:" + ex.Message);
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-gvData_ItemCommand:" + ex.Message);
        }
    }
    protected void gv_Price_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        try
        {
            if (Session["Username"] != null)
            {
                string commandName = e.CommandName;
                int ID = Convert.ToInt32(e.CommandArgument.ToString());//Lay ID 
                helper = new DatabaseHelper();
                pro = new ProProduct();
                if (commandName == "EditItem")
                {
                    try
                    {
                        RadPageView2.Selected = true;
                        TabStrip1.SelectedIndex = 3;
                        int[] listLocationID = new int[1] { 0 };
                        DataTable dt = loadPrice(ID, 0, listLocationID);
                        if (dt.Rows.Count > 0)
                        {
                            txtPrice.Text = String.Format("{0:N0}", Convert.ToDouble(dt.Rows[0]["Price"]));
                            cbProduct.SelectedValue = dt.Rows[0]["ProductID"].ToString();
                            txtLastUpdatedBy.Text = dt.Rows[0]["LastUpdatedBy"].ToString();
                            txtLastUpdatedDateTime.Text = dt.Rows[0]["LastUpdatedDateTime"].ToString();
                            btnSavePrice.Enabled = true;
                            IList<RadListBoxItem> collection = rlbLocation.Items;
                            foreach (RadListBoxItem item in collection)//List Location
                            {
                                string str = dt.Rows[0]["LocationID"].ToString();
                                if (item.Value.ToString() == str)
                                {
                                    item.Checked = true;
                                    item.Focus();
                                    //break;
                                }
                                else
                                    item.Checked = false;
                            }
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("Product Page-gv_Price_ItemCommand-EditItem:" + ex.Message);
                    }
                }
                else if (commandName == "DeleteItem")
                {
                    try
                    {
                        db = new DBDataContext();
                        //db.Connection.Open();
                        DefinitionPrice obj = db.DefinitionPrices.FirstOrDefault(x => x.ID == ID);

                        obj.LastUpdatedDateTime = DateTime.Now;
                        obj.LastUpdatedBy = Session["Username"].ToString();
                        obj.Status = 'I';
                      
                        db.SubmitChanges();
                        JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa tin thành công!");
                        gv_Price.Rebind();
                    }
                    catch (Exception ex)
                    {
                        ControlUtil.LogError("Product Page-gv_Price_ItemCommand-DeleteItem:" + ex.Message);
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Xóa không thành công!");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-gv_Price_ItemCommand:" + ex.Message);
        }
    }
    protected void gv_Price_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        try
        {

            //Ham phan trang: Paging
            if (RadPageView3.Selected)
            {
                TabStrip1.SelectedIndex = 2;
                gv_Price.Height = 250;
                gv_Price.Visible = true;
                getPriceSearch();
            }
            else
            {
                gv_Price.DataSource = new DataTable();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Product Page-gvData_NeedDataSource:" + ex.Message);
        }
    }
    protected void btnSavePrice_Click(object sender, EventArgs e)
    {
        if (Session["Username"] != null)
        {
            try
            {
                #region Validate Data
                TabStrip1.SelectedIndex = 3;
                if (string.IsNullOrEmpty(cbProduct.SelectedValue.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn sản phẩm!");
                    cbProduct.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtPrice.Text.Trim()))
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập giá bán!");
                    txtPrice.Focus();
                    return;
                }
                if (txtPrice.Text.Trim() == "0")
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập giá bán phải lớn hơn 0!");
                    txtPrice.Focus();
                    return;
                }

                if (rlbLocation.CheckedItems.Count == 0)
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn tỉnh/thành!");
                    rlbLocation.Focus();
                    return;
                }
                #endregion End Validate Data

                db = new DBDataContext();
                #region Insert Data

                string strProductID = string.Empty;
                string strLocationID = string.Empty;
                IList<RadListBoxItem> collection = rlbLocation.CheckedItems;
                foreach (RadListBoxItem item in collection)
                {
                    strProductID = cbProduct.SelectedValue;
                    strLocationID = item.Value.ToString();
                    var list = (from a in db.DefinitionPrices
                                where a.Status == 'A'
                                       && a.ProductID == Convert.ToInt32(strProductID)
                                       && a.LocationID == Convert.ToInt32(strLocationID)
                                select a).SingleOrDefault();
                    if (list == null)//Insert
                    {
                        DefinitionPrice obj = new DefinitionPrice();
                        obj.ProductID = Convert.ToInt32(strProductID);
                        obj.LocationID = Convert.ToInt32(strLocationID);
                        obj.Price = Convert.ToDouble(Utils.KillChars(txtPrice.Text.Trim()));
                        obj.LastUpdatedBy = Session["Username"].ToString();
                        obj.CreatedBy = Session["Username"].ToString();
                        obj.CreatedDateTime = DateTime.Now;
                        obj.LastUpdatedDateTime = DateTime.Now;
                        obj.Status = 'A';
                        db.Insert<DefinitionPrice>(obj);
                        db.SubmitChanges();
                    }
                    else//Update
                    {
                        list.Price = Convert.ToDouble(Utils.KillChars(txtPrice.Text.Trim()));
                        list.LastUpdatedBy = Session["Username"].ToString();
                        list.LastUpdatedDateTime = DateTime.Now;
                        db.SubmitChanges();
                    }
                }
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Lưu thành công!");
                btnSavePrice.Enabled = false;
                gv_Price.Rebind();
                #endregion End Insert Data
            }
            catch(Exception ex)
            {
                ControlUtil.LogError("Product Page-btnSavePrice_Click:" + ex.Message.ToString());
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Thông báo lỗi: Lưu không thành công, vui lòng kiểm tra dữ liệu!");
            }
        } 
    }
    protected void btnNewPrice_Click(object sender, EventArgs e)
    {
        
        //Response.Redirect("/Product", false);
        TabStrip1.SelectedIndex = 3;
        //RadPageView2.Selected = true;
        txtPrice.Text = "";
        btnSavePrice.Enabled = true;
        Utils.loadProductToComboPrice(cbProduct, 1, "R");
        Utils.loadLocationToRadListBox(rlbLocation);
        gv_Price.DataSource = new DataTable();
        gv_Price.DataBind();
    }
    protected void btnSearchPrice_Click(object sender, EventArgs e)
    {
        getPriceSearch();
        gv_Price.DataBind();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        getDataSearch();
        //ProProduct pro = new ProProduct();

        DataTable tblresult = dtProductExport(pro);
        if (tblresult.Rows.Count > 0)
        {
            ExcelUtil.ExportDataTableToExcel2007FromRadGrid(tblresult, gvData, "sanpham");
        }
        else
        {
            JavascriptUtil.LoadMessage(Page, false, "Không có dữ liệu xuất Excel !!!");
        }
    }
}